/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aiaudio.processing.base;

import aiaudio.lastfm.hbase.CannotCreateTableException;
import aiaudio.Application;
import aiaudio.database.TableDescriptor;
import aiaudio.database.tables.StatisticsTable;
import aiaudio.processing.MainTableGroup;
import java.io.IOException;
import java.util.Calendar;

/**
 *
 * @author nastya
 */
public abstract class TimeMeasuredAlgorithm<Par extends AlgorithmParameters> {

    protected MainTableGroup mainTableGroup;
    protected String algorithmName;
    protected Par parameters;

    public void setParameters(Par parameters) {
        this.parameters = parameters;
    }

    public TimeMeasuredAlgorithm(MainTableGroup mainTableGroup, String algorithmName) {
        this.mainTableGroup = mainTableGroup;
        this.algorithmName = algorithmName;
    }
    private long timeStart;

    protected void startMeasurement() {
        timeStart = Calendar.getInstance().getTimeInMillis();
    }

    protected void endMeasurement() throws IOException {
        long timeEnd = Calendar.getInstance().getTimeInMillis();
        writeMeasurement(timeEnd - timeStart);
    }

    private void writeMeasurement(long time) throws IOException {
        String tableName = mainTableGroup.getStatisticsTableGroup().getStaticsticsTable();
        TableDescriptor d = Application.database().getByName(tableName);
        StatisticsTable.addTime(d.getTable(), algorithmName, time);
    }

    public void start() throws IOException, CannotCreateTableException, InterruptedException, ClassNotFoundException {
        createTemporaryTables();
        startMeasurement();

        writeParameters(parameters);

        process();

        measureAll();

        endMeasurement();
        removeTemporaryTables();
    }

    protected abstract void removeTemporaryTables();

    protected abstract void createTemporaryTables() throws IOException;

    protected abstract void process() throws IOException, CannotCreateTableException, InterruptedException, ClassNotFoundException ;

    protected abstract void measureAll() throws IOException;

    protected abstract void writeParameters(Par parameters)  throws IOException;
}
